package com.dh.example.io.listener;

import cn.hutool.core.util.StrUtil;
import com.corundumstudio.socketio.AuthorizationResult;
import com.corundumstudio.socketio.HandshakeData;
import com.dh.example.io.configuration.WebSocketConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 授权侦听器
 *
 * @author yolo
 * @date 2024/3/12 10:50
 * @mail yolo_215@163.com
 */
@Component
@EnableConfigurationProperties(WebSocketConfig.class)
@Slf4j
public class AuthorizationListener {


    /**
     * 打印日志结果开关，动态刷新
     */
    @Value("${login.token.switch:true}")
    public boolean loginTokenSwitch;

    private WebSocketConfig webSocketConfig;

    public AuthorizationListener(WebSocketConfig webSocketConfig) {
        this.webSocketConfig = webSocketConfig;
    }


    /**
     * 被授权
     *
     * @param handshakeData 握手数据
     * @return {@code AuthorizationResult}
     */
    public AuthorizationResult isAuthorized(HandshakeData handshakeData) {
        if (!loginTokenSwitch) {
            // 跳过token判断
            return new AuthorizationResult(true);
        }
        // 根据用户查询token，查询对应的权限
        String clientType = handshakeData.getSingleUrlParam("clientType");
        if (StrUtil.isBlank(clientType)) {
            log.error("clientType is null");
            return new AuthorizationResult(false);
        }

        String token = handshakeData.getSingleUrlParam("token");

        // 根据各个端查询token存储的位置 pc、app 路径不同  （获取token，查询对应的redis是否存在权限）
        String defaultRedisPath = "pc";
        if (webSocketConfig.getClientRedisPathMap().containsKey(clientType)) {
            defaultRedisPath = webSocketConfig.getClientRedisPathMap().get(clientType);
        }
        if (StrUtil.isNotBlank(token) && "token".equals(token)) {
            return new AuthorizationResult(true);
        }

        log.info("token is null;权限校验不通过");
        return new AuthorizationResult(false);


    }
}
